package com.fy.login;

import com.fy.login.internal.MetadataCallback;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.UnsupportedCallbackException;
import java.io.IOException;

/**
 * @author zhufeifei 2022/8/9
 **/

public final class NetCallbackHandler extends SimpleCallbackHandler {

    private String ip;
    private int port;
    private Long loginDate;

    public NetCallbackHandler(Role role, String username, char[] password) {
        super(role, username, password);
    }

    public NetCallbackHandler(Role role, String username, char[] password, String ip, int port) {
        this(role, username, password);
        this.ip = ip;
        this.port = port;
    }

    @Override
    @SuppressWarnings(value = "unchecked")
    public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
        if (loginDate == null) {
            loginDate = System.currentTimeMillis();
        }
        super.handle(callbacks);
        for (Callback c : callbacks) {
            if (c instanceof MetadataCallback) {
                ((MetadataCallback<NetMetadata>) c).setMetadata(new NetMetadata(this.role, this.username, this.ip, this.port, loginDate));
            }
        }
    }
}
